package eva

import (
	"context"
	"time"
	"trusteva/app/eva/model"

	"trusteva/app/eva/internal/svc"
	"trusteva/app/eva/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListAppLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewListAppLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListAppLogic {
	return &ListAppLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ListAppLogic) ListApp(req *types.ListAppRo) (resp *types.ListAppRsp, err error) {
	sess := l.svcCtx.DB.WithContext(l.ctx).Model(&model.App{})
	if req.AppName != "" {
		sess = sess.Where("AppName like ?", "%"+req.AppName+"%")
	}
	if req.AppId != "" {
		sess = sess.Where("AppId=?", req.AppId)
	}
	if req.DeviceId != "" {
		sess = sess.Where("DeviceId=?", req.DeviceId)
	}
	if req.UserId != "" {
		sess = sess.Where("UserId=?", req.UserId)
	}

	var total int64
	if err := sess.Count(&total).Error; err != nil {
		return nil, err
	}

	//查询规则总数
	var ruleTotal int64
	sess2 := l.svcCtx.DB.WithContext(l.ctx).Model(&model.Rule{})
	if req.UserId != "" {
		sess2 = sess2.Where("UserId=?", req.UserId)
	}
	if err := sess2.Count(&ruleTotal).Error; err != nil {
		return nil, err
	}

	var beans []model.App
	if err := sess.Order("ID DESC").Limit(req.Size).Offset((req.Page - 1) * req.Size).
		Find(&beans).Error; err != nil {
		return nil, err
	}

	resp = new(types.ListAppRsp)
	resp.Total = total
	resp.RuleTotal = ruleTotal
	for _, v := range beans {
		var ac = types.ListAppData{
			Id:        v.ID,
			AppName:   v.AppName,
			AppId:     v.AppId,
			DeviceId:  v.DeviceId,
			Memo:      v.Memo,
			CreatedAt: v.CreatedAt.Format(time.RFC3339),
			UpdatedAt: v.UpdatedAt.Format(time.RFC3339),
			UserId:    v.UserId, // TODO 新增字段
		}
		resp.Items = append(resp.Items, ac)
	}
	return
}
